package com.micro.ai.commons.exception;

import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.commons.constant.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理全局异常
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleGlobalException(GlobalException e, HttpServletRequest request) {
        log.warn("全局异常: code={}, message={}, data={}", e.getCode(), e.getMessage(), e.getData(), e);
        return ApiResponse.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Object> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: code={}, message={}, data={}", e.getCode(), e.getMessage(), e.getData(), e);
        return ApiResponse.error(e.getCode(), e.getMessage(), e.getData());
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Object> handleSystemException(SystemException e, HttpServletRequest request) {
        log.error("系统异常: code={}, message={}, data={}", e.getCode(), e.getMessage(), e.getData(), e);
        return ApiResponse.error(e.getCode(), e.getMessage(), e.getData());
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<Map<String, List<String>>> handleValidationException(ValidationException e, HttpServletRequest request) {
        log.warn("参数验证异常: code={}, message={}, errors={}", e.getCode(), e.getMessage(), e.getErrors(), e);
        return ApiResponse.error(e.getCode(), e.getMessage(), e.getErrors());
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<Map<String, List<String>>> handleBindException(BindException e, HttpServletRequest request) {
        log.warn("参数绑定异常: {}", e.getMessage(), e);
        
        Map<String, List<String>> errors = e.getFieldErrors().stream()
                .collect(Collectors.groupingBy(
                        FieldError::getField,
                        Collectors.mapping(FieldError::getDefaultMessage, Collectors.toList())
                ));
        
        return ApiResponse.error(ErrorCodeEnum.A0010.getCode(), "参数验证失败", errors);
    }

    /**
     * 处理方法参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<Map<String, List<String>>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.warn("方法参数验证异常: {}", e.getMessage(), e);
        
        Map<String, List<String>> errors = e.getFieldErrors().stream()
                .collect(Collectors.groupingBy(
                        FieldError::getField,
                        Collectors.mapping(FieldError::getDefaultMessage, Collectors.toList())
                ));
        
        return ApiResponse.error(ErrorCodeEnum.A0010.getCode(), "参数验证失败", errors);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.warn("非法参数异常: {}", e.getMessage(), e);
        return ApiResponse.error(ErrorCodeEnum.A0010.getCode(), e.getMessage());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: {}", e.getMessage(), e);
        return ApiResponse.error(ErrorCodeEnum.B0001.getCode(), "系统内部错误");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常: {}", e.getMessage(), e);
        return ApiResponse.error(ErrorCodeEnum.B0001.getCode(), "系统内部错误");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ApiResponse.error(ErrorCodeEnum.B0001.getCode(), "系统内部错误");
    }
    
    
}